package com.example.socketdemo;

import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.TextView;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;

import butterknife.BindView;


public class SocketConnectorThread extends Thread {


    private Manager manager = Manager.getManager();
    private int PORT;
    private String IP;
    Handler handler;
    private SendMsgThread sendMsgThread=null;
    private ReceiveMsgThread receiveMsgThread=null;
    private Socket socket = new Socket();



    //构造方法(ip, port)
    public SocketConnectorThread(String ip, int port, Handler handler) {
        this.IP = ip;
        this.PORT = port;
        this.handler = handler;
    }

    @Override
    public void run() {
        try {
            socket.connect(new InetSocketAddress(IP, PORT));
            if (socket.isConnected()) {
                manager.setSocket(socket);  //当Socket连接成功后将对象传给manager的引用
                Message msg = handler.obtainMessage();
                msg.what = 1; //发送成功
                msg.obj = "连接成功";
                handler.sendMessage(msg);
            }
            else {
                Message msg = handler.obtainMessage();
                msg.what = 0; //发送失败
                msg.obj = "连接失败";
                handler.sendMessage(msg);
            }
        } catch (IOException e) {
            Message msg = handler.obtainMessage();
            msg.what = -1; //没找到网络之类的情况
            msg.obj = "连接异常";
            handler.sendMessage(msg);
        }
    }

//    public void message() {
//            sendMsgThread = new SendMsgThread(manager.getSocket(), handler);
//            receiveMsgThread = new ReceiveMsgThread(manager.getSocket(), handler);
//            receiveMsgThread.start();
//            sendMsgThread.start();
//            manager.setSendMsgThread(sendMsgThread);
//            manager.setReceiveMsgThread(receiveMsgThread);
//            Log.d("TAGGGGG", "message: " + "打开消息通道");
//    }
}

